package com.example.sample.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.EventLog;
import android.util.EventLog.Event;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.aidl.IRemoteService;
import com.example.app.BaseActivity;
import com.example.sample.R;
import com.example.sample.SampleApp;
import com.example.sample.util.MPermissionDelegate;

import net.liteheaven.xblib.common.io.MemUtil;
import net.liteheaven.xblib.common.log.Log4jManager;
import net.liteheaven.xblib.common.log.XLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 
 * 主界面 
 * @author  LiangYu
 * @data:  2015-1-5 下午6:43:28 
 * @version:  V1.0
 */
public class MainActivity extends BaseActivity {
	
	private static final String TAG = "MainActivity";
	private ListView mFunctionList;
	private FunctionAdapter mFunctionAdapter;
	private Timer mCheckTopTimer;
	
	// 功能映射结构
	public static class FunctionMapping{
		public String desc;
		public Class<?> cls;
		
		public FunctionMapping(String desc, Class<?> cls){
			this.desc = desc;
			this.cls = cls;
		}
	}

	final static private FunctionMapping mMapping[] = new FunctionMapping[]{
			new FunctionMapping("启动前台服务", ForegroundTestActivity.class),
			new FunctionMapping("registerNetworkCallback监听网络变化", RegisterNetworkCallbackActivity.class),
			new FunctionMapping("端外推送拉起指定页面的研究", WakeUpActivity.class),
			new FunctionMapping("Activity启动方式", LaunchModeActivity.class),
			new FunctionMapping("状态机", FSMActivity.class),
			new FunctionMapping("获取屏幕尺寸", ScreenSizeActivity.class),
			new FunctionMapping("内存抖动测试", MemJitterActivity.class),
			new FunctionMapping("多级数据的选择", MultiLayerSelectorActivity.class),
			new FunctionMapping("通知和PendingIntent", NotificationAndPendingIntentActivity.class),
			new FunctionMapping("lottie/获取硬件序列号/画三角形", LottieActivity.class),
			new FunctionMapping("硬编解码MediaCodec", MediaCodecActivity.class),
			new FunctionMapping("打开wifi", WifiActivity.class),
			new FunctionMapping("安卓M权限测试", PermissionActivity.class),
			new FunctionMapping("MVP测试", MvpTestActivity.class),
			new FunctionMapping("下拉刷新(pull to refresh ListView)", PullToRefreshListViewActivity.class),
			new FunctionMapping("线程停止测试", ThreadActivity.class),
			new FunctionMapping("友盟测试", UmengTestActivity.class),
			new FunctionMapping("HTTP请求发送", HttpRequestActivity.class),
			new FunctionMapping("imageloader", ImageLoaderActivity.class),
			new FunctionMapping("网络诊断", NetworkDoctorActivity.class),
			new FunctionMapping("系统下载服务测试", DownloadManagerActivity.class),
			new FunctionMapping("跨活动传递回调（序列化参数可以本地化）", MethodRebornActivity.class),
			new FunctionMapping("CursorLoader的使用", LoaderActivity.class),
			new FunctionMapping("Fragment空指针问题", FragmentProblemActivity.class),
			new FunctionMapping("安卓路径API", DirActivity.class),
			new FunctionMapping("AttachBaseContext", AttachBaseContextActivity.class),
			new FunctionMapping("ClassLoader", ClassLoaderActivity.class),
			new FunctionMapping("OOM", OOMActivity.class),
			new FunctionMapping("脏矩形", DirtyRectActivity.class),
			new FunctionMapping("root专题", RootActivity.class),
			new FunctionMapping("measureSpec专题", MeasureActivity.class),
			new FunctionMapping("手势监听器", GestureActivity.class),
			new FunctionMapping("飘心", FloatHeartActivity.class),
			new FunctionMapping("ViewPager的用法", ViewPagerActivity.class),
			new FunctionMapping("圆形渐变图片", RoundImageViewActivity.class),
			new FunctionMapping("SimpleListAdapter", SimpleCursorAdapterActivity.class),
			new FunctionMapping("横向列表spacing", HListViewActivity.class),
			new FunctionMapping("ViewGroup和Layout的一点差别", VGAddLayoutActivity.class),
			new FunctionMapping("文字测宽", TextViewMeasureActivity.class),
			new FunctionMapping("JNI调用", HelloJniActivity.class),
			new FunctionMapping("“加载中”弹窗+load raw+自定义Toast动画", LoadingPopupActivity.class),
			new FunctionMapping("基站测试", BaseStationActivity.class),
			new FunctionMapping("父子触摸事件", TouchEventActivity.class),
			new FunctionMapping("列表滚动", ListViewScrollActivity.class),
			new FunctionMapping("TextView改变Translate和Scale", TextViewTransformActivity.class),
			new FunctionMapping("清理内存", CleanUpActivity.class),
			new FunctionMapping("系统信息", BuildInfoActivity.class),
			new FunctionMapping("GridLayout用法", GridLayoutActivity.class),
			new FunctionMapping("正则表达式测试", RegularExpressionActivity.class),
			new FunctionMapping("包信息查询&字符编码检查&无Emoji编辑框", ApkInfoActivity.class),
			new FunctionMapping("选择文件", FileBrowseActivity.class),
			new FunctionMapping("视图滚动", ScrollActivity.class),
			new FunctionMapping("进程管理", ProcessInfoActivity.class),
			new FunctionMapping("滤镜", FilterTransfromActivity.class),
			new FunctionMapping("黏性列表", StickyListViewActivity.class),
			new FunctionMapping("WebView", WebViewActivity.class),
			new FunctionMapping("VideoView", VideoViewActivity.class),
			new FunctionMapping("可扩展图片文字", SpannableActivity.class),
	};
	
	/**
	 * 
	 * 功能适配器 
	 * @author  LiangYu
	 * @data:  2015-3-4 下午6:29:23 
	 * @version:  V1.0
	 */
	public class FunctionAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return mMapping.length;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			Context ctx = MainActivity.this;
			LayoutInflater li = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View v = null;
			if (convertView == null){
				v = li.inflate(R.layout.item_function_list, parent, false);
				TextView tv = (TextView)v.findViewById(R.id.functionText);
				v.setTag(tv);
			}
			else{
				v = convertView;				
			}
			TextView tv = (TextView)v.getTag();
			tv.setText(mMapping[position].desc);
			/*v.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dispatchClick(position);
				}
			});*/
			return v;
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final String [] requiredPermissions = new String [] {
				Manifest.permission.READ_PHONE_STATE,
				Manifest.permission.READ_EXTERNAL_STORAGE,
				Manifest.permission.WRITE_EXTERNAL_STORAGE,
		};
		checkPermissions(requiredPermissions, new MPermissionDelegate.PermissionResultCallback() {
			@Override
			public void onSuccess() {
				onCreated();
			}

			@Override
			public void onFailure(boolean isBan) {
				finish();
			}
		});
	}

	private void onCreated(){

		Log4jManager.getInstance().configure(false);

		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		//monitorActivityStart();
		testLogCollector();

		Log.i(TAG, "onCreate");

		mFunctionList = (ListView)findViewById(R.id.functionList);

		mFunctionAdapter = new FunctionAdapter();
		mFunctionList.setAdapter(mFunctionAdapter);
		mFunctionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				dispatchClick(position);
			}
		});

		int per = MemUtil.getAvaMemPercentage(this);
		per = per;

		testLogil();
		testLeak();
		testGetClass();
		if (false){
			testService();

			File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
			boolean exists = f.exists();
			Toast.makeText(this, "" + f.toString() + " exists=" + exists, Toast.LENGTH_SHORT).show();
			writeTest();
		}
		testDBUpdate();
		Toast t = Toast.makeText(this, "测试测试测试测试测试测试", Toast.LENGTH_SHORT);
		//ReflectUtil.invokeMethod(t, "show", null, null);
		//startCheckTop();

		try {
			Class clazz = Class.forName("android.app.ActivityThread");
			Method m = clazz.getDeclaredMethod("currentActivityThread");
			m.invoke(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean writeTest(){
		try {
			File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/plugin/writeTest.txt");
			FileOutputStream fs = new FileOutputStream(f);

			String text = "aaaaaaaaaaaaaaaaaaaaaa";
			byte[] bytes = text.getBytes();

			for (int i=0; i<2; ++i){
				fs.write(bytes, 0, bytes.length);
			}
			fs.close();
		}
		catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();		
		stopCheckTop();
	}
	
	private void dispatchClick(int index){
		Class<?> cls = mMapping[index].cls;
		if (cls != null){
			Intent intent = new Intent(getApplicationContext(), cls);
			startActivity(intent);
		}
	}

    public static class LeakTest{
        public Runnable r = new Runnable() {
            @Override
            public void run() {
                Toast.makeText(SampleApp.getApp(), "leak test", Toast.LENGTH_SHORT);
            }
        };
    }

    /**
     * 结论：这种不会引起空指针
     */
    private void testLeak(){
        LeakTest lt = new LeakTest();
        Runnable ref = lt.r;
        lt = null;
        System.gc();

        ref.run();
    }

    /**
     * 结论：获取的是实例的类
     */
    private void testGetClass(){
        Context ctx = getApplicationContext();
        Log.i(TAG, "className="+ctx.getClass());
    }

    private void testLogil(){
    }
    
    private void testLogCollector(){
    }
    
    private IRemoteService mService;
    private ServiceConnection mConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG, "onServiceDisconnected");
			mService = null;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG, "onServiceConnected");
			mService = IRemoteService.Stub.asInterface(service);
			try {
				mService.action();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
    
    private void testService(){
    	// 模拟作为客户端绑定服务    	
		Intent bindIntent = new Intent("com.example.aidl.START_REMOTE_SERVICE");
    	// 在安卓某个版本之后，意图必须显式地指明包名
    	bindIntent.setPackage(getPackageName());
    	boolean result = getApplicationContext().bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
		XLog.d(TAG, "bindService result = " + result);
    }
    
    private void startCheckTop(){
    	
    	final TimerTask tt = new TimerTask() {
			
			@Override
			public void run() {
				ActivityManager am = (ActivityManager) MainActivity.this
						.getSystemService(Context.ACTIVITY_SERVICE);
				List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
				if (!taskInfo.isEmpty()) {
					RunningTaskInfo rti = taskInfo.get(0);
					ComponentName cn = rti.topActivity;
					String packageName = cn.getPackageName();
					String className = cn.getClassName();
					Log.i(TAG, "top = " + className + " [" + packageName + "]");
				}
			}
		};
    	
		if (mCheckTopTimer == null){
			mCheckTopTimer = new Timer();
			mCheckTopTimer.schedule(tt, 1000, 1000);
		}
	}
    
    private void stopCheckTop(){
    	if (mCheckTopTimer != null){
    		mCheckTopTimer.cancel();
    		mCheckTopTimer = null;
    	}
    }
    
    private void monitorActivityStart(){
    	new Thread(){
    		@Override
    		public void run() {
    			super.run();
    			
    			while (true) {
    				try {  
        	    	    int tagCode = EventLog.getTagCode("am_proc_start");  
        	    	    Collection<Event> output = new ArrayList<EventLog.Event>();  
        	    	    EventLog.readEvents(new int[] { tagCode }, output);  
        	    	    for (Event event : output) {  
        	    	        // PID, UID, Process Name, Type, Component  
        	    	        Object[] objects = (Object[]) event.getData();  
        	    	        
        	    	        int pid = (Integer) objects[0];
        	    	        int uid = (Integer) objects[1];
        	    	        String processName = (String)objects[2];
        	    	        String type = (String)objects[3];
        	    	        ComponentName componentName = ComponentName  
        	    	                .unflattenFromString(objects[4].toString());
        	    	        String packageName = componentName.getPackageName();
        	    	        
        	    	        if (type.equals("activity")){
        	    	        	Log.i(TAG, "" + objects.length
        	    	        			/*+ "pid=" + pid 
        	    	        			+ " uid=" + uid 
        	    	        			+ " process=" + processName*/
        	    	        			+ " type=" + objects[3].toString() 
        	    	        			+ " package=" + packageName);
        	    	        }
        	    	    }  
        	    	} catch (IOException e) {  
        	    	    e.printStackTrace();  
        	    	}
    				
    				try {
    					Thread.sleep(5000);
					} catch (Exception e) {
					}    				
				}    			
    		}
    	}.start();
    	
    }

	public static class DBHelper extends SQLiteOpenHelper{

		public DBHelper(Context context){
			super(context, "com.example.sample.db", null, 3);
		}


		@Override
		public void onCreate(SQLiteDatabase db) {
			XLog.i(TAG, "DBHelper onCreate");

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			XLog.i(TAG, "db ver from " + oldVersion + " to " + newVersion);
		}
	}

	/**
	 * 证明version不变不会到onUpgrade
	 */
	private void testDBUpdate(){
		DBHelper dbHelper = new DBHelper(this);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
	}
}
